package com.blog.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.blog.article.entity.Article;
import com.blog.article.entity.ArticleTag;
import com.blog.article.entity.Blog;
import com.blog.article.entity.Tag;
import com.blog.article.entity.VO.*;
import com.blog.article.mapper.*;
import com.blog.article.service.BlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.platform.commons.util.CollectionUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
//import sun.text.CollatorUtilities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 苏离
 * @since 2021-12-10
 */

@SuppressWarnings("all")
@Slf4j
@Service
@Transactional
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    ArticleTagMapper articleTagMapper;
    @Autowired
    TagMapper tagMapper;
    private List<BlogPlus> getList(List<Blog> blogs){
        List<BlogPlus> list=new ArrayList<>();
        blogs.forEach(blog ->{
            String userId = blog.getUserId();
            String userName = blogMapper.getUserName(userId);
            BlogPlus blogPlus = new BlogPlus(
                    blog.getBlogTitle(),
                    blog.getUserId(),
                    userName,
                    blog.getBlogViews(),
                    blog.getBlogCollections(),
                    blog.getArticleId(),
                    blog.getBlogTime(),
                    blog.getLastTime());
            list.add(blogPlus);
        });
        return list;
    }
    /**获取所有用户公开文章
     *
     * @param count
     * @return
     */
    @Override
    public Map<String,Object> getBlog(Integer count) {
        //用来存放blog信息
        List<BlogPlus> list=new ArrayList<>();
        Map map=new HashMap();
        List<Blog> blogs = blogMapper.getBlog(count);

        //文章总数
        Integer blogCount = blogMapper.getBlogCount();
        map.put("allCount", blogCount);
        //将数据赋给blogPlus实体类
        blogs.forEach(blog ->{
            String userId = blog.getUserId();
            String userName = blogMapper.getUserName(userId);
            BlogPlus blogPlus = new BlogPlus(
                    blog.getBlogTitle(),
                    blog.getUserId(),
                    userName,
                    blog.getBlogViews(),
                    blog.getBlogCollections(),
                    blog.getArticleId(),
                    blog.getBlogTime(),
                    blog.getLastTime());
            list.add(blogPlus);
        });
        map.put("blogs", list);
        return map;
    }

    /**
     * 根据文章id获取文章
     * @param id
     * @param count
     * @return
     */
    @Override
    public Map<String, Object> getBlogById(String id, Integer count) {
        Map map=new HashMap();
        List<Blog> blogs = blogMapper.getBlogById(id,count);
        Integer blogCount = blogMapper.getCountById(id);
        map.put("allCount", blogCount);
        //将数据赋给blogPlus实体类
        List<BlogPlus> list = getList(blogs);
        map.put("blogs", list);
        return map;
    }

    /**
     * 更新观看数量views
     * @param userId
     * @param articleId
     * @return
     */
    public boolean updateViews(String userId,Integer articleId){
        QueryWrapper<Blog> queryWrappe=new QueryWrapper();
        queryWrappe.eq("user_id", userId).eq("article_id", articleId);
        Blog blog = blogMapper.selectOne(queryWrappe);
        if(!ObjectUtils.isEmpty(blog))
            return false;
        UpdateWrapper<Blog> updateWrapper=new UpdateWrapper();
        return  blogMapper.updateViews(articleId);
    }
    /**
     * 根据tagId获取所有文章
     * @param id
     * @param count
     * @return
     */
    @Override
    public Map<String, Object> getBlogByTag(Integer id, Integer count) {
        Map map=new HashMap();
        List<Integer> articleIdByTagId = blogMapper.getArticleIdByTagId(count, id);
        List<Integer> blogCount = blogMapper.getArticleIdByTagIdAll(id);
        List<Integer> allArticleId = blogMapper.getAllArticleId();
        List<Integer> collect = blogCount.parallelStream().filter(item -> allArticleId.contains(item)).collect(Collectors.toList());
        List<BlogPlus> list=new ArrayList<>();
        map.put("allCount", collect.size());
        articleIdByTagId.forEach(articleId ->{
            Blog blog = blogMapper.getBlogByTag(articleId);
            if(!ObjectUtils.isEmpty(blog)) {
                String userId = blog.getUserId();
                String userName = blogMapper.getUserName(userId);
                BlogPlus blogPlus = new BlogPlus(
                        blog.getBlogTitle(),
                        blog.getUserId(),
                        userName,
                        blog.getBlogViews(),
                        blog.getBlogCollections(),
                        blog.getArticleId(),
                        blog.getBlogTime(),
                        blog.getLastTime());
                list.add(blogPlus);
            }
        });
        map.put("blogs", list);
        return map;
    }

    /**
     * 根据title模糊查询文章
     * @param title
     * @param count
     * @return
     */
    @Override
    public Map<String, Object> getBlogByTitle(String title) {
        Map<String,Object> map=new HashMap<>();
        Integer titleCount = blogMapper.getTitleCount(title);
        map.put("allCount", titleCount);
        List<Blog> blogByTitle = blogMapper.getBlogByTitle(title);
        List<BlogPlus> list = getList(blogByTitle);
        map.put("blogs", list);
        return map;
    }

    /**
     * 获取单个用户的所有文章
     * @param userId 用户id
     * @param pageSize 当前页数
     * @return
     */
    @Override
    public Map<String, Object> getBlog(String userId, Integer pageSize,Integer limit) {
        pageSize=(pageSize-1)*limit;
        List<Blog> userBlogs = blogMapper.getUserBlog(userId, pageSize,limit);
        Map<String,Object> map=new HashMap<>();
        if(ObjectUtils.isEmpty(userBlogs))
            return null;
        List<UserBlog> list=new ArrayList<>();
        Integer blogCount = blogMapper.getBlogCounts(userId);
        map.put("blogCount", blogCount);
        userBlogs.forEach(blog -> {
            UserBlog userBlog=new UserBlog(
                    blog.getUserId(),
                    blog.getBlogTitle(),
                    blog.getBlogViews(),
                    blog.getBlogCollections(),
                    blog.getArticleId(),
                    blog.getBlogTime(),
                    blog.getLastTime(),
                    blog.getBlogType());
            list.add(userBlog);
        });
        map.put("userBlog", list);
        return map;
    }

    /**
     * 获取所有所有tag
     * @return
     */
    @Override
    public Map<String, Object> getTags() {
        List<Tag> tags = blogMapper.getTags();
        Map<String, Object> map=new HashMap<>();
        if(ObjectUtils.isEmpty(tags)) {
            log.info("标签库为空");
            return null;
        }
        map.put("tags", tags);
        return map;
    }

    /**
     * 根据id获取文章,限当前用户
     * @param id 文章id
     * @return 文章的内容：标题，最后修改时间，文章内容
     */
    @Override
    public Map<String, Object> getArticleById(Integer id) {
        ArticleVO articleById = blogMapper.getArticleById(id);
        List<String> tags = blogMapper.getTagById(id);
        ArticleVO article= articleById.setTags(tags);
        Map<String,Object> map=new HashMap<>();
        map.put("article", article);
        return map;
    }

    /**
     * 根据id获取文章,所有用户
     * @param id 文章id
     * @return
     */
    public Map<String,Object> getAnyArticleById(Integer id){
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("article_id", id);
        Blog blog = blogMapper.selectOne(queryWrapper);
        String userId = blog.getUserId();
        UserVO userInfo = blogMapper.getUserInfo(userId);
        Article article = articleMapper.selectOne(queryWrapper);
        List<ArticleTag> ArticleTags = articleTagMapper.selectList(queryWrapper);
        List<Tag> tags=new ArrayList<>();
        ArticleTags.forEach(tag ->{
            QueryWrapper queryWrappers=new QueryWrapper();
            queryWrappers.eq("tag_id", tag.getTagId());
            Tag tag1 = tagMapper.selectOne(queryWrappers);
            tags.add(tag1);
        });
        Map<String,Object> map=new HashMap<>();
        map.put("blog", blog);
        map.put("article", article);
        map.put("tags", tags);
        map.put("userInfo", userInfo);
        return map;
    }
    /**创建文章
     *
     * @param blogVO
     * @return
     */
    @Override
    public boolean createArticle(BlogVO blogVO) {
        //将文章内容插入，获得文章id
        Article article=new Article();
        article.setArticleContent(blogVO.getTextarea());
        articleMapper.insert(article);
        Integer articleId = article.getArticleId();
        //创建blog对象
        Blog blog=new Blog(
                blogVO.getTitle(),
                articleId,
                blogVO.getUserId(),
                blogVO.getRadio()
        );
        int insert = blogMapper.insert(blog);
        if(insert==0){
            return false;
        }
        List<Integer> tagsId = blogVO.getTagsId();
        tagsId.forEach(tagId ->{
            articleTagMapper.insert(new ArticleTag(articleId,tagId));
        });
        return true;
    }

    /**更新文章
     *
     * @param blogVO
     * @return
     */
    @Override
    public boolean updateArticle(BlogVO blogVO) {
        //创建blog对象
        Blog blog=new Blog();
        blog.setBlogTitle(blogVO.getTitle());
        blog.setBlogType(blogVO.getRadio());
        //更新blog
        QueryWrapper<Blog> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("article_id", blogVO.getArticleId());
        blogMapper.update(blog, queryWrapper );
        //更新article
        Article article=new Article();
        article.setArticleContent(blogVO.getTextarea());
        QueryWrapper<Article> articleUpdateWrapper = new QueryWrapper<>();
        articleUpdateWrapper.eq("article_id", blogVO.getArticleId());
        articleMapper.update(article,articleUpdateWrapper);
        //删除tag
        articleTagMapper.delete(new UpdateWrapper<ArticleTag>()
                .eq("article_id", blogVO.getArticleId()));
        //更新文章tag
        List<Integer> tagsId = blogVO.getTagsId();
        Integer articleId = blogVO.getArticleId();
        tagsId.forEach(tagId ->{
            articleTagMapper.insert(new ArticleTag(articleId, tagId));
        });
        return true;
    }

    /**
     * 根据文章id删除文章
     * @param id
     * @return
     */
    @Override
    public boolean deleteArticle(String userId,Integer id) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("article_id", id);
        articleMapper.deleteByAttach(id);
        articleMapper.deleteComment(id);
        int delete = blogMapper.delete(queryWrapper);
        int delete1 = articleTagMapper.delete(queryWrapper);
        int delete2 = articleMapper.deleteById(id);
        if(delete>0 && delete1>0 && delete2>0)
            return true;
        return false;
    }

    @Override
    public Map<String, Object> getAllBlog(Integer pageSize, Integer limit) {
        pageSize=(pageSize-1)*limit;
        List<Blog> userBlogs = blogMapper.getAllBlog(pageSize,limit);
        Map<String,Object> map=new HashMap<>();
        if(ObjectUtils.isEmpty(userBlogs))
            return null;
        List<UserBlog> list=new ArrayList<>();
        Integer blogCount = blogMapper.getAllBlogCount();
        map.put("blogCount", blogCount);
        userBlogs.forEach(blog -> {
            UserBlog userBlog=new UserBlog(
                    blog.getUserId(),
                    blog.getBlogTitle(),
                    blog.getBlogViews(),
                    blog.getBlogCollections(),
                    blog.getArticleId(),
                    blog.getBlogTime(),
                    blog.getLastTime(),
                    blog.getBlogType());
            list.add(userBlog);
        });
        map.put("userBlog", list);
        return map;
    }

    @Override
    public Map<String, Object> getAllBlogByTitle(String title, Integer pageSize, Integer limit) {
        pageSize=(pageSize-1)*limit;
        List<Blog> userBlogs = blogMapper.getAllBlogByTitle(title,pageSize,limit);
        int count=0;
        Map<String,Object> map=new HashMap<>();
        if(ObjectUtils.isEmpty(userBlogs))
            return null;
        List<UserBlog> list=new ArrayList<>();
        Integer blogCount = blogMapper.getAllBlogByTitleCount(title);
        map.put("blogCount", blogCount);
        userBlogs.forEach(blog -> {
            UserBlog userBlog=new UserBlog(
                    blog.getUserId(),
                    blog.getBlogTitle(),
                    blog.getBlogViews(),
                    blog.getBlogCollections(),
                    blog.getArticleId(),
                    blog.getBlogTime(),
                    blog.getLastTime(),
                    blog.getBlogType());
            list.add(userBlog);
        });
        map.put("userBlog", list);
        return map;
    }

}
